<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<link rel="stylesheet" type="text/css"
	href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
<link rel="stylesheet" type="text/css"
	href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>
<script type="text/javascript"
	src="<c:url value="/static/js/common.js"/>"></script>
<script>
	var Address = [];//下拉数组
	var addIdCost = 0;
	$.ajax({
		async : false,
		url : "<c:url value='/mater/pulldownMaterType.do?space=0'/>",
		type : "post",
		success : function(data) {
			Address = data;
			if (typeof (Address) == 'string') {
				Address = JSON.parse(Address);
			}
		}
	});
	function initList(listDisplayEId,quotationId) {
		$('#' + listDisplayEId).datagrid({
			url : "<c:url value='/quotationCust/findQuotation.do'/>" +"?quotationId="+quotationId,
			nowrap : false,
			striped : true,
			collapsible : true,
			remoteSort : true,
			notSelectByRow : false,
			columns : [ [ {
                field : 'check',
                title : '',
                width : 30,
                align : 'center',
                formatter : formatRadio
            },{
				field : 'orderId',
				title : 'id',
				width : 100,
				align : 'center',
				hidden : true
			}, {
				field : 'materType',
				title : '材料种类',
				width : 100,
				align : 'center',
				editor : {
					type : 'combobox',
					options : {
						data : Address,
						valueField : "materType",
						textField : "materTypename",
						editable : false
					}
				}
			}, {
				field : 'raiseAmount',
				title : '提价百分比',
				width : 100,
				align : 'center',
				editor : {
					type : 'text',
					options : {
						required : true
					}
				}
			} ] ],
			onLoadError : function() {
				$.messager.alert('错误', '获取数据失败，请与管理员联系！', 'error');
			},
			onClickRow : function(rowIndex) {
				$(".myrad").prop("checked", false);
				$(".myrad").eq(rowIndex).prop("checked", true);
			}
		});
	};
	
	function combox(){
		$('#quotationCombobox').combobox({
            url : '<c:url value='/quotationCust/pullDownQuotation.do'/>',
            editable : false, //不可编辑状态  
            cache : false,
            panelHeight : '150',
            valueField : 'quotationId',
            textField : 'quotationName',
            onChange : function(newValue, oldValue) {
               initList('listDisplay',newValue);
               setTimeout( 'getRows()',300);
            }
        });
	}
	$(document).ready(function() {
		combox();
		initList('listDisplay',0);
	});
	function getRows(){
		var rows = $('#listDisplay').datagrid('getRows');
        beginEditList(rows, '#listDisplay','orderId');
        var max=0;
        for (var i = 0; i < rows.length; i++) {
        	if(rows[i]['orderId']>max){
        		max = rows[i]['orderId'];
        	}
        }
        addIdCost =max +1;
	}
	function beginEditList(rows, list, id) {
        for (var i = 0; i < rows.length; i++) {
            var rowIndex = $(list).datagrid('getRowIndex', rows[i][id]);
            $(list).datagrid('beginEdit', rowIndex);
        }
    }
	function excel() {
        $('#AddFoodForm')
                .form(
                        'submit',
                        {
                            url : '<c:url value='/quotationCust/quotationCustForSupplier.do'/>', //查询提交路径
                            onSubmit : function() {

                                var rows = $('#listDisplay')
                                        .datagrid('getRows');
                                for (var i = 0; i < rows.length; i++) {
                                    var rowIndex = $('#listDisplay').datagrid(
                                            'getRowIndex', rows[i]['orderId']);
                                    $('#listDisplay').datagrid('endEdit',
                                            rowIndex);
                                    //check 
                                    if (!isNumberAndNoZero(rows[i]['raiseAmount'])) {
                                        $.messager.alert("提示", "提价百分比请填写数字！",
                                                'info');
                                        beginEditList(rows, '#listDisplay',
                                                'orderId');
                                        return false;
                                    }
                                    if (rows[i]['raiseAmount'] < 100) {
                                        $.messager.alert("提示", "百分比不能小于100！",
                                                'info');
                                        beginEditList(rows, '#listDisplay',
                                                'orderId');
                                        return false;
                                    }
                                }
                                var row = $('#listDisplay').datagrid('getRows');
                                var jsonFater;

                                if (row.length == 0) {

                                } else {
                                    var userList = new Array();
                                    for (var i = 0; i < row.length; i++) {
                                        var jsonSun = "{materType:'"
                                                + row[i]['materType']
                                                + "',raiseAmount:'"
                                                + row[i]['raiseAmount']
                                                + "',orderId:'"
                                                + row[i]['orderId'] + "'}";
                                        userList.push(jsonSun);
                                    }
                                }
                                jsonFater = JSON.stringify(userList);
                                $("#datejson").attr("value", jsonFater);
                                
                                setTimeout( 'getRows()',300);
                                return $('#AddFoodForm').form('validate');
                                /*  var form = new FormData();
                                 form.append("datejson", jsonFater); // 可以增加表单数据
                                 form.append("supId", 0); // 可以增加表单数据

                                 // XMLHttpRequest 对象
                                 var xhr = new XMLHttpRequest();
                                 xhr.open("post", '<c:url value='/quotationCust/quotationCustForSupplier.do'/>', true);
                                 xhr.onload = function() {
                                    alert(1);
                                 };
                                 xhr.send(form); */
                            },
                            success : function(data) {
                                data = eval("(" + data + ")");
                                if (data.success) {
                                    $.messager.alert("提示", "提交成功！", 'info');
                                } else {
                                    var message = "";
                                    if (data.msg == "msg002") {
                                        message = "所选择日期的材料订单已经下单完成，如需重新选择请删除已有订单。";
                                    } else if (data.msg == "msg001") {
                                        message = "选择材料的时间已过，请联系采购部。";
                                    } else {
                                        message = data.msg;
                                    }
                                    $.messager.alert("提示", message, 'warning');
                                }
                            },
                            error : function() {
                                $.messager.alert("错误", "系统错误，请联系管理员！", 'error');
                                return;
                            }
                        });

    }
	function addRow() {
		$('#listDisplay').datagrid('appendRow', {
			orderId : addIdCost
		});
		addIdCost = addIdCost + 1;
		var lastIndex = $('#listDisplay').datagrid('getRows').length - 1;
		$('#listDisplay').datagrid('beginEdit', lastIndex);
	}
	function addQuotation() {
		$('#AddFoodForm')
				.form(
						'submit',
						{
							url : '<c:url value='/quotationCust/saveQuotation.do'/>', //查询提交路径
							onSubmit : function()//提交按钮相应函数
							{
								$('#quotationName').attr('value', $('#quotationNameCopy').val());
								//周子意
								var rows = $('#listDisplay')
										.datagrid('getRows');
								for (var i = 0; i < rows.length; i++) {
									var rowIndex = $('#listDisplay').datagrid(
											'getRowIndex', rows[i]['orderId']);
									$('#listDisplay').datagrid('endEdit',
											rowIndex);
									
									//check 
                                    if (!isNumberAndNoZero(rows[i]['raiseAmount'])) {
                                        $.messager.alert("提示", "提价百分比请填写数字！",
                                                'info');
                                        beginEditList(rows, '#listDisplay',
                                                'orderId');
                                        return false;
                                    }
                                    if (rows[i]['raiseAmount'] < 100) {
                                        $.messager.alert("提示", "百分比不能小于100！",
                                                'info');
                                        beginEditList(rows, '#listDisplay',
                                                'orderId');
                                        return false;
                                    }
								}
								var row = $('#listDisplay').datagrid('getRows');
								if (row.length == 0) {
									$.messager.alert('提示', '没有设置定价！', 'info');
									return false;
								} else {
									var userList = new Array();
									var jsonFater;
									for (var i = 0; i < row.length; i++) {

										var jsonSun = "{materType:'"
												+ row[i]['materType']
												+ "',raiseAmount:'"
												+ row[i]['raiseAmount']
										        + "',orderId:'"
                                                + row[i]['orderId']+ "'}";
										userList.push(jsonSun);
									}
									jsonFater = JSON.stringify(userList);
									var str = "json=" + jsonFater;
									document.getElementsByName("datejson")[0].value = jsonFater;
									return $('#AddFoodForm').form('validate');
								}
							},
							success : function(data) {
								data = eval("(" + data + ")");
								if (data.success) {
									$.messager.alert("提示", "提交成功！", 'info');
									combox();
									setTimeout( 'getRows()',300);
								} else {
									var message = "";
									if (data.msg == "msg002") {
										message = "所选择日期的材料订单已经下单完成，如需重新选择请删除已有订单。";
									} else if (data.msg == "msg001") {
										message = "选择材料的时间已过，请联系采购部。";
									} else {
										message = data.msg;
									}
									$.messager.alert("提示", message, 'warning');
								}
							},
							error : function() {
								$.messager.alert("错误", "系统错误，请联系管理员！", 'error');
								return;
							}
						});

	}
	
	function deleteQuotation(){
		if($('#quotationCombobox').combobox('getValue') ==''){
			$.messager.alert("提示", "请选择方案！", 'warning');
            return false;
		}else{
			var quotationId = $('#quotationCombobox').combobox('getValue');
			
			$.ajax({
	            async : false,
	            url : "<c:url value='/quotationCust/deleteQuotation.do?quotationId='/>"+quotationId,
	            type : "post",
	            success : function(data) {
	            	data = eval("(" + data + ")");
                    if (data.success) {
                        $.messager.alert("提示", "删除成功！", 'info');
                        combox();
                        $('#listDisplay').datagrid('reload');
                        setTimeout( 'getRows()',300);
                        
                    } else{
                    	var message = "系统错误";
                        $.messager.alert("提示", message, 'warning');
                    }
	            }
	        });
		}
	}
	 
    function formatRadio(value,rowData,rowIndex){
        return value="<input type='radio' class='myrad'  name='radioMater' />";
    }
</script>
</head>
<body>
	<table width="98%">
		<tr>
			<td>
				<table id="listDisplay" title="机构列表" iconCls="icon-list"
					singleSelect=false idField="orderId" loadMsg="请稍候......"
					pagination="true" pageSize="20" pageList="[10,20,30,40,50]"
					toolbar="#tb" sortName="shopId" rownumbers="true" sortOrder="asc">
					<thead>
						<tr>
						    <th field="check"  width="30" align="center" ></th> 
							<th field="orderId" width="25" align="center" hidden="true"></th>
							<th field="materType" width="40" sortable="true"
								editor="combobox">种类</th>
							<th field="raiseAmount" width="140" sortable="true" editor="text">提价百分比</th>

						</tr>
					</thead>
				</table>
			</td>
		</tr>
	</table>
	<div id="tb" style="padding: 5px; height: auto">
		<div>
			新增方案名: <input class="easyui-validatebox" style="width: 80px" id="quotationNameCopy" name="quotationNameCopy"> 
			<a href="#" onclick="addQuotation()" class="easyui-linkbutton" iconCls="icon-save" plain="true">保存方案</a>
			<br /> 提价方案选择: <input class="easyui-combobox" name="quotationCombobox" id="quotationCombobox">
			<!-- <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改方案</a>  -->
			<a href="#" onclick="deleteQuotation()" class="easyui-linkbutton" iconCls="icon-cut" plain="true">删除方案</a> 
			<br /> <a href="#" onclick="excel()" class="easyui-linkbutton" iconCls="icon-print">下载客户报价单</a>
		</div>
		<div style="margin-bottom: 5px">
			<a href="#" onclick="addRow()" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a> 
			<a href="#" onclick="addRow()" class="easyui-linkbutton" iconCls="icon-remove" plain="true"></a>
		</div>
	</div>
	<form id="AddFoodForm" name="AddFoodForm" method="post"  enctype="multipart/form-data" action="userlist.txt"
                        onsubmit="return searchDGData(this.id,'listDisplay');">
		<input class="easyui-validatebox" type="hidden" name="supId" id="supId" value="0" />
		<input class="easyui-validatebox" type="hidden" name="quotationName" id="quotationName" /> 
		<input class="easyui-validatebox" type="hidden" name="datejson" />

		</from>
</body>


</html>